package com.webtest.controller;

import com.fasterxml.jackson.databind.annotation.JsonAppend;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.webtest.dao.BookMapper;
import com.webtest.dao.BookShelfMapper;
import com.webtest.entity.*;
import com.webtest.service.*;
import com.webtest.service.impl.ShelfServiceImpl;
import com.webtest.vo.SearchBooks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
public class BookController {

    @Autowired
    private BookService bookService;
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private BorrowService borrowService;

    @Autowired
    private UserService userService;
    @Autowired
    private ShelfService shelfService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private BookShelfMapper bookShelfMapper;

    //图书列表
    @RequestMapping("/books")
    public String toBookList(Model model, @RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum, HttpSession session) {
        List<Book> allBook = bookService.getAllBook();
        // 获取所有书架
        List<Shelf> allShelf = shelfService.getAllShelf();


        Map forObject = restTemplate.getForObject("http://ip-api.com/json/", Map.class);
        String lat = forObject.get("lat").toString();
        String lng = forObject.get("lon").toString();

        model.addAttribute("lng", lng);
        model.addAttribute("lat", lat);
        model.addAttribute("allShelf", allShelf);



        // 根据书架分类查询书籍信息
        SearchBooks searchBooks = new SearchBooks();
        for (Shelf shelf : allShelf) {
            searchBooks.setShelfId(shelf.getShelfId());
            List<Book> books = bookShelfMapper.getAllBookByShelfId(searchBooks);
            shelf.setBooks(books);
        }

        Iterator<Shelf> iterator = allShelf.iterator();
        while (iterator.hasNext()) {
            Shelf next = iterator.next();
            if (next == null || CollectionUtils.isEmpty(next.getBooks())) {
                iterator.remove();
            }
        }

        PageInfo<Book> bookPageInfo = new PageInfo<>(allBook);
        model.addAttribute("pageInfo", bookPageInfo);
        model.addAttribute("allBook", allBook);
        User user = (User) session.getAttribute("user");
        User userById = userService.findUserById(user.getId());
        model.addAttribute("userMessage", userById);
        return "book";
    }

    //条件搜索
    @PostMapping("/books/search")
    public String searchBooks(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,  @RequestParam() Integer shelfId,
                              Model model, SearchBooks searchBooks, HttpSession session) {

        List<Book> allBook;
        if (shelfId != null && shelfId != 0){
            // 查询书架下的所有书籍信息
            SearchBooks searchs = new SearchBooks();
            searchs.setShelfId(Long.valueOf(shelfId));
            allBook = bookShelfMapper.getAllBookByShelfId(searchs);
        }else{
            allBook = bookMapper.searchBookByIdOrName1(searchBooks);
        }
        // 获取所有书架
        List<Shelf> allShelf = shelfService.getAllShelf();
        model.addAttribute("allShelf", allShelf);

        // 根据书架分类查询书籍信息
        SearchBooks searchs = new SearchBooks();
        for (Shelf shelf : allShelf) {
            searchs.setShelfId(shelf.getShelfId());
            List<Book> books = bookShelfMapper.getAllBookByShelfId(searchs);
            shelf.setBooks(books);
        }

        Iterator<Shelf> iterator = allShelf.iterator();
        while (iterator.hasNext()) {
            Shelf next = iterator.next();
            if (next == null || CollectionUtils.isEmpty(next.getBooks())) {
                iterator.remove();
            }
        }

        List<List<Book>> groupedBooks = new ArrayList<>();
        for (int i = 0; i < allBook.size(); i += 3) {
            List<Book> subList = allBook.subList(i, Math.min(i + 3, allBook.size()));
            groupedBooks.add(subList);
        }

        PageInfo<Book> bookPageInfo = new PageInfo<>(allBook);
        model.addAttribute("pageInfo", bookPageInfo);
        User user = (User) session.getAttribute("user");
        User userById = userService.findUserById(user.getId());
        model.addAttribute("userMessage", userById);
        System.out.println(allBook);
        model.addAttribute("groupedBooks", groupedBooks);
        model.addAttribute("allBook", allBook);
        return "newBook :: allBook";

    }

    //图书列表
    @RequestMapping("/goodBooks")
    public String toGoodBookList(Model model, @RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum, HttpSession session) {

        List<Book> allBook = bookMapper.getAllGoodBook();
        for (Book book : allBook) {
            List<Comment> comments = commentService.listComment(book.getBookId());
            book.setComments(comments);

        }

        model.addAttribute("allBook", allBook);

        PageInfo<Book> bookPageInfo = new PageInfo<>(allBook);
        System.out.println(bookPageInfo.getList() + "###############");
        model.addAttribute("pageInfo", bookPageInfo);
        User user = (User) session.getAttribute("user");
        User userById = userService.findUserById(user.getId());
        model.addAttribute("userMessage", userById);
        return "goodBook";
    }

    @RequestMapping("/newBook")
    public String newGoodBook(Model model, @RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum
            , @RequestParam() Integer shelfId
            , HttpSession session) {

        // 查询书架下的所有书籍信息
        SearchBooks searchBooks = new SearchBooks();
        searchBooks.setShelfId(Long.valueOf(shelfId));
        List<Book> allBook = bookShelfMapper.getAllBookByShelfId(searchBooks);


        // 对所有书籍进行分组
        List<List<Book>> groupedBooks = new ArrayList<>();
        for (int i = 0; i < allBook.size(); i += 3) {
            List<Book> subList = allBook.subList(i, Math.min(i + 3, allBook.size()));
            groupedBooks.add(subList);
        }

        PageInfo<Book> bookPageInfo = new PageInfo<>(allBook);
        model.addAttribute("pageInfo", bookPageInfo);
        User user = (User) session.getAttribute("user");
        User userById = userService.findUserById(user.getId());
        model.addAttribute("userMessage", userById);
        model.addAttribute("groupedBooks", groupedBooks);
        model.addAttribute("allBook", allBook);
        return "newBook";
    }

    //条件搜索
    @PostMapping("/goodBooks/search")
    public String searchGoodBooks(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                  Model model, SearchBooks searchBooks, HttpSession session) {
        PageHelper.startPage(pageNum, 6);
        List<Book> booklist = bookMapper.searchBookByIdOrName(searchBooks);

        for (Book book : booklist) {
            List<Comment> comments = commentService.listComment(book.getBookId());
            book.setComments(comments);

        }
        PageInfo<Book> bookPageInfo = new PageInfo<>(booklist);
        System.out.println(booklist + "###############");
        model.addAttribute("pageInfo", bookPageInfo);
        User user = (User) session.getAttribute("user");
        User userById = userService.findUserById(user.getId());
        model.addAttribute("userMessage", userById);
        return "goodBook :: pageList";
    }

    //图书借阅
    @GetMapping("/books/{bookId}/borrow/{shelfId}")
    @Transactional
    public String borrowBook(@PathVariable Integer bookId, @PathVariable Integer shelfId,RedirectAttributes attributes, HttpSession session) {
        User user = (User) session.getAttribute("user");
        //当前用户id
        Integer stuId = user.getId();

        // 根据书籍及和书架查询图书库存信息
        SearchBooks searchBooks = new SearchBooks();
        searchBooks.setBookId(bookId);
        searchBooks.setShelfId(Long.valueOf(shelfId));
        BookShelf bookShelf = bookShelfMapper.getBookShelf(searchBooks).get(0);
        if (bookShelf.getCount() <= 0) {
            attributes.addFlashAttribute("message", "对不起，该书籍已经借光，请稍后再试");
            return "redirect:/books";
        }

        //获取当前用户所有借阅信息
        Borrow borrow = new Borrow();
        borrow.setBookId(bookId);
        borrow.setStuId(stuId);
        borrow.setStatus(1);
        List<Borrow> borrows = borrowService.selectBorrowList(borrow);
        if (borrows.size() > 0) {
            attributes.addFlashAttribute("message", "对不起，您已经借了该书，请勿重复借书");
            return "redirect:/books";
        }

        // 借阅书籍，该书架下书籍 -1
        bookShelf.setCount(bookShelf.getCount() - 1);
        bookShelfMapper.updateBookShelfByCount(bookShelf);

        //用户新增借阅
        Date date = new Date();
        borrowService.insertBorrow(bookId, stuId, date);
        attributes.addFlashAttribute("message", "恭喜您，借阅成功");
        return "redirect:/books";
    }

    @GetMapping("/bookXQ")
    @Transactional
    public String bookXQ(@RequestParam() Integer bookId, RedirectAttributes attributes, HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        User userById = userService.findUserById(user.getId());
        model.addAttribute("userById", userById);
        //当前用户id
        Integer stuId = user.getId();
        Book bookById = bookService.findBookById(bookId);
        List<Comment> comments = commentService.listComment(bookId);
        bookById.setComments(comments);
        model.addAttribute("book", bookById);
        attributes.addFlashAttribute("message", "恭喜您，借阅成功");
        return "bookXQ";
    }

    @GetMapping("/book/shelf/{shelfId}/{lng}/{lat}")
    @Transactional
    public String bookShelf(@PathVariable Integer shelfId, @PathVariable String lng, @PathVariable String lat, RedirectAttributes attributes, HttpSession session, Model model) {
        Shelf shelf = new Shelf();
        shelf.setShelfId(Long.valueOf(shelfId));
        shelf.setLng(lng);
        shelf.setLat(lat);
        shelfService.updateById(shelf);
        attributes.addFlashAttribute("message", "恭喜您，借阅成功");
        return "redirect:/books";
    }
}
